package otcpro_service

import (
	"beta/pkg/e"
	"beta/pkg/logger"
	"beta/pkg/util"
	"github.com/tidwall/gjson"
	"time"
)

type SettleProduct struct {
	ProductID        string `json:"productId"`
	ProductVersionID string `json:"productVersionId"`
}

type SettleProductInfo struct {
	SettleProduct `json:"settleProduct"`
}

type SettleOrder struct {
	BaseInfo `json:"baseInfo"`
	SettleProductInfo `json:"productInfo"`
	ContactInfo `json:"contactInfo"`
	OrderRemark `json:"orderRemark"`
}

func (otcpro OtcProService) CreateSettleOrder(productId, productVersionId string) (string, error)  {

	host := otcpro.Hosts["otcpro"].AppDomain
	url := host + "/otcpro/v1/order/settleOrder/save"
	baseInfo := BaseInfo{
		AccessID:     "",
		OrderType:    "0",
		PurchaserID:  otcpro.CustomerId,
		ServiceType:  "01",
		SalesChannel: "50",
		TerminalType: "1",
		OrderMode:    "2",
	}

	settleProductInfo := SettleProductInfo{SettleProduct{
		ProductID:        productId,
		ProductVersionID: productVersionId,
	}}

	contactInfo := ContactInfo{
		ContactName: otcpro.FullName,
		Gender:      "",
		Role:        "",
		Mobile:      "",
		Phone:       "",
		Email:       "",
	}
	
	orderRemark := OrderRemark{
		SignerID:     e.GetOperatorId(otcpro.Operator),
		OperatorType: "2",
		OperatorID:   e.GetOperatorId(otcpro.Operator),
	}

	settleOrder := SettleOrder{
		BaseInfo:          baseInfo,
		SettleProductInfo: settleProductInfo,
		ContactInfo:       contactInfo,
		OrderRemark:       orderRemark,
	}

	logger.ZapLogger.Infow("【创建后付费订单】", "请求参数", settleOrder, "traceId", otcpro.traceId)

	cookie := util.GetCookie(util.BossCookieName, otcpro.Token)
	httpClient := util.NewHttpClientWithCookie(3 * time.Second, cookie).R()

	resp, respErr := httpClient.SetHeaders(e.GetHeaderMap(e.JsonHeader)).SetBody(settleOrder).Post(url)
	logger.ZapLogger.Infow("【创建后付费订单】", "请求结果", resp, "traceId", otcpro.traceId)

	if respErr != nil {
		return "", respErr
	}

	orderId := gjson.Get(resp.String(), "data.orderId").String()

	return orderId, nil

}
